package mypack.threadtest;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreTest {

	public static void main(String[] args) {

		ExecutorService service = Executors.newCachedThreadPool();
		final Semaphore sph = new Semaphore(3);
		for (int i = 0; i < 10; i++) {
			Runnable target = new Runnable() {
				@Override
				public void run() {
					try {
						sph.acquire();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("Thread-----------------> "+ Thread.currentThread().getName() + "   --->"+ (3 - sph.availablePermits()));
					try {
						Thread.sleep(new Random().nextInt(2000));
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
                    System.out.println(Thread.currentThread().getName()+"-----------> over ...." );
                    sph.release();
				}
			};
			service.execute(target);
		}
		
		service.shutdown();
	}

}
